package com.wnxy.article.service.impl;

import com.wnxy.article.entity.Article;
import com.wnxy.article.entity.User;
import com.wnxy.article.mapper.ArticleMapper;
import com.wnxy.article.mapper.UserMapper;
import com.wnxy.article.service.ArticleService;
import com.wnxy.article.vo.ArticleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<ArticleVo> findAll() {
        // 查询所有
        List<Article> list = articleMapper.findAll();
        // 构造返回的vo
        List<ArticleVo> result = new ArrayList<>();

        // 遍历从数据库中查询的数据，封装为vo
        for (Article article : list) {
            User user = userMapper.findById(article.getUserid());

            ArticleVo vo = new ArticleVo();
            // 对象拷贝，把article对象拷贝到空的vo对象中。同名同类型属性才会拷贝
            BeanUtils.copyProperties(article,vo);
            vo.setUserName(user.getName());
            // 添加到返回的集合
            result.add(vo);
        }

        return result;
    }
}
